﻿using MengCC.Plugin.SDK;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace MengCC.Plugin.Command
{
    class Program
    {
        static void Main(string[] args)
        {
            PluginContext pluginContext = new PluginContext(args);
            var options = pluginContext.GetOptions<Options>();
            var cmdpath = Path.Combine(pluginContext.Wordspace, $"{ Guid.NewGuid()}.bat");

            //var options = new Options
            //{
            //    PowerSellPath = @"C:\Windows\System32\WindowsPowerShell\v1.0",
            //    IsUsePowerSell = false,
            //    Script = "java -version"
            //};
            //var cmdpath = Path.Combine(@"D:\VSProject\MengCC\MengCC.App\WorkSpaces\1\p1\p123", $"{ Guid.NewGuid()}.bat");

            File.WriteAllText(cmdpath, options.Script, Encoding.ASCII);
            var processInfo = options.IsUsePowerSell ? new ProcessStartInfo(options.PowerSellPath, cmdpath) : new ProcessStartInfo(cmdpath);

            processInfo.RedirectStandardInput = true;
            processInfo.RedirectStandardOutput = true;
            processInfo.CreateNoWindow = true;
            processInfo.RedirectStandardError = true;
            processInfo.Verb = "runas";

            var process = new Process();
            process.StartInfo = processInfo;
            process.Start();


            var task=Task.Factory.StartNew(() =>
            {
                while (!process.HasExited)
                {
                    var input = Console.ReadLine();
                    using (var inputStream = process.StandardInput)
                    {
                        inputStream.WriteLine(input);
                        inputStream.Flush();
                    }
                }
            });


            //开始读取

            using (var sr = process.StandardOutput)
            {
                while (sr.BaseStream.CanRead && !sr.EndOfStream)
                {
                    var content = sr.ReadLine();
                    Console.WriteLine(content);
                }
            }
            using (var sr = process.StandardError)
            {
                while (sr.BaseStream.CanRead && !sr.EndOfStream)
                {
                    var content = sr.ReadLine();
                    Console.WriteLine(content);
                }

                if (!process.HasExited)
                {
                    process.Kill();
                }
            }
            if (File.Exists(cmdpath)) File.Delete(cmdpath);

        }
    }
}
